/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ddd.service;

import com.ddd.context.Parameters;
import com.ddd.entity.Negotiation;
import com.ddd.util.HibernateUtil;
import com.ddd.util.Util;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class NegotiationService extends BaseService {

    private Parameters para;
    private LogService logService;

    public NegotiationService(HttpServletRequest request) {
        para = new Parameters(request);
        logService = new LogService(request);
    }

    public Negotiation load(String id) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();

        Negotiation negotiation = (Negotiation) session.load(Negotiation.class, id);
        //Hibernate.initialize(journal);

        tx.commit();
        session.close();

        return negotiation;
    }

    public ArrayList loadAll() {
        ArrayList result = new ArrayList();
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        Criteria criteria = session.createCriteria(Negotiation.class);
        Iterator iter = criteria.list().iterator();
        while (iter.hasNext()) {
            result.add(iter.next());
        }
        tx.commit();
        session.close();
        para.setTotalSize(result.size());
        return result;
    }

    public void save(Negotiation negotiation) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        negotiation.setCid(para.getUsername());
        negotiation.setCtime(Util.getTodayWithTime());
        session.save(negotiation);
        tx.commit();
        session.close();
    }

    public void update(Negotiation negotiation) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        negotiation.setUid(para.getUsername());
        negotiation.setUtime(Util.getTodayWithTime());
        session.update(negotiation);
        tx.commit();
        session.close();
    }

    public void delete(Negotiation negotiation) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        session.delete(negotiation);
        tx.commit();
        session.close();
    }
}
